<!--
  <upload-img
      :img="file"   {name,url}
      :upload="true"   // 上传展示，抑或只能展示
      :dark="false"    // 置灰图片
      v-on:updateImg="update"
    >
    </upload-img>
 -->
<template>
  <div id="upload">
	    <div class="public-input-wrap" @click="$tool.clickIdDom(img.name)">
        <input
          type="file"
          :id="img.name"
          :upload="upload"
          :dark="dark"
          :disabled="!upload || dark"
          name="idBackInput"
          @change="uploadImg($event, img.name)">
        <div class="cross" v-if="crossShow">
          <span class="upright"></span>
          <span class="across"></span>
        </div>
        <slot></slot>
        <img
          v-if="img.url && !dark"
          :src="img.url"
          alt="">
      </div>
    <mt-spinner class="loading" type="fading-circle" :size="60" color="#063359" v-show="uploading">
    </mt-spinner>
  </div>
</template>
<script>
  import Vue from 'vue'
  import { Spinner } from 'mint-ui'
  Vue.component(Spinner.name, Spinner)
	export default {
		name: 'upload-img',
    props: {
      img: {
        type: Object,
        default () {
          return {
            name: 'img',
            url: ''
          }
        }
      },
      upload: {
        type: Boolean,
        default: true
      },
      dark: {
        type: Boolean,
        default: false
      }
    },
		data () {
			return {
        uploading: false
			}
		},
    computed: {
      crossShow () {
        return this.img.url ? false : this.upload && !this.dark
      }
    },
    components: {
      Spinner
    },
		methods: {
			uploadImg(event, img) {
        // console.log('event', event)
        this.uploading = true
        let formData = new FormData()
        formData.append('file', event.target.files[0])
        this.$http.axios({
          url: this.$http.imgURL,
          method: 'post',
          data: formData
        }).then((res) => {
          this.uploading = false
          if (res.data.error === 0) {
            this.img.url = res.data.data.img_url
            this.$emit('updateImg', res.data.data.img_url, img)
          } else if (res.data.error === 1) {
            alert(res.data.msg)
          }
        }).catch((error) => {
          this.uploading = false
          console.log(error)
        })
      }
		}
	}
</script>
<style lang="scss" scoped>
  #upload {
    position: relative;
    .loading {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%)
    }
  }
</style>
